package com.cjz.servlet;

import com.cjz.dao.DButil;
import com.cjz.domain.User;
import org.codehaus.jackson.map.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "LoginServlet",urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String username = request.getParameter("userName");
        String password = request.getParameter("password");
        String role = request.getParameter("role");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> flags = new HashMap<>();
        // 声明数据库操作类
        DButil db = new DButil();
        // 取得数据库连接
        db.getConn();
        ResultSet rs = db.getResultSet("Select * from user where username = ? and password = ? and role = ?", new String[]{username, password, role});
        try {
            flags.put("flag",true);
            if (!rs.next()) {
                flags.put("flag",false);
            }
            else {
                User user = new User(username, password, rs.getString("realname"), role);
                session.setAttribute("user", user);
            }
            out.print(mapper.writeValueAsString(flags));
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            // 关闭数据库连接
            db.release();
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
